package com.lottery.material.controller.portal.article;

import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.jedis.JedisClient;
import com.lottery.material.pojo.article.ArticleInfo;
import com.lottery.material.pojo.article.ArticlePictureInfo;
import com.lottery.material.pojo.article.ArticleTextInfo;
import com.lottery.material.pojo.article.CompetitionInfo;
import com.lottery.material.pojo.circle.CircleInfo;
import com.lottery.material.pojo.circle.CircleMemberInfo;
import com.lottery.material.pojo.conf.MenuLevelConfig;
import com.lottery.material.pojo.page.PageData;
import com.lottery.material.pojo.portaluser.CollectInfo;
import com.lottery.material.pojo.portaluser.DeleteArticleRecord;
import com.lottery.material.pojo.portaluser.FollowInfo;
import com.lottery.material.pojo.portaluser.PortalUserInfo;
import com.lottery.material.pojo.promotion.PromotionRuleConfig;
import com.lottery.material.pojo.transaction.TransactionRecord;
import com.lottery.material.pojocustom.article.ArticleCompetitionInfoCustom;
import com.lottery.material.pojocustom.article.ArticleInfoCustom;
import com.lottery.material.resolver.CustomException;
import com.lottery.material.service.portal.article.ArticleCompetitionInfoService;
import com.lottery.material.service.portal.article.ArticleInfoService;
import com.lottery.material.service.portal.article.ArticlePictureInfoService;
import com.lottery.material.service.portal.article.ArticleTextInfoService;
import com.lottery.material.service.portal.circle.CircleMemberInfoService;
import com.lottery.material.service.portal.menu.MenuLevelConfigService;
import com.lottery.material.service.portal.promotion.PromotionRuleConfigService;
import com.lottery.material.service.portal.transaction.TransactionRecordService;
import com.lottery.material.service.portal.user.*;
import com.lottery.material.util.*;
import com.lottery.material.vo.portal.article.ArticleInfoAuthorVo;
import com.lottery.material.vo.portal.article.ArticleInfoDetailVo;
import com.lottery.material.vo.portal.article.ArticlePromotionRuleVo;
import com.lottery.material.vo.portal.article.ArticleRewardReasonVo;
import com.lottery.material.vo.portal.competition.CompetitionArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Description:    文章详情接口Controller
 * Author:         sunny
 * CreateDate:     2019-04-23 15:07
 */
@RequestMapping("/portal/article")
@Slf4j
@Controller
public class ArticleInfoDetailController extends BaseController {

    @Autowired
    @Qualifier("jedisClientCluster")
    private JedisClient jedisClient;

    @Autowired
    private ArticleInfoService articleInfoService;
    @Autowired
    private TransactionRecordService transactionRecordService;
    @Autowired
    private CircleMemberInfoService circleMemberInfoService;
    @Autowired
    private FollowInfoService followInfoService;
    @Autowired
    private CollectInfoService collectInfoService;
    @Autowired
    private MenuLevelConfigService menuLevelConfigService;
    @Autowired
    private ArticleTextInfoService articleTextInfoService;
    @Autowired
    private ArticlePictureInfoService articlePictureInfoService;
    @Autowired
    private ArticleCompetitionInfoService articleCompetitionInfoService;
    @Autowired
    private PromotionRuleConfigService promotionRuleConfigService;
    @Autowired
    private PortalUserInfoService portalUserInfoService;
    @Autowired
    private RewardReasonDictService rewardReasonDictService;
    @Autowired
    private DeleteArticleRecordService deleteArticleRecordService;

    /**
     * description: 获取文章详情
     * author sunny
     * createDate 2019-04-23 下午 3:17
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getArticleDetail", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getArticleDetail(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String articleId = reqParamMap.get("articleId");
        if (StringUtils.isBlank(articleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "articleId");
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            //根据文章id查询详情部分信息
            ArticleInfoCustom articleInfoCustom = articleInfoService.findArticleDetailByArticleId(articleId);
            if (Objects.isNull(articleInfoCustom)) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_NOT_EXIST_FAIL);
            }

            articleInfoService.updateReadTotalByArticleId(articleId); //更新文章阅读量

            //用户信息
            PortalUserInfo portalUserInfo = articleInfoCustom.getPortalUserInfo();
            //圈子信息
            CircleInfo circleInfo = articleInfoCustom.getCircleInfo();

            //数据封装
            ArticleInfoAuthorVo author = new ArticleInfoAuthorVo();
            author.setUserId(articleInfoCustom.getUserId());
            author.setNickName(articleInfoCustom.getNickName());
            author.setUserIcon(portalUserInfo.getUserIcon());
            author.setUserType(String.valueOf(portalUserInfo.getUserType()));

            ArticleInfoDetailVo articleInfoDetailVo = new ArticleInfoDetailVo();
            articleInfoDetailVo.setArticleId(articleInfoCustom.getArticleId());
            articleInfoDetailVo.setCreateTime(CalendarUtil.showTime(articleInfoCustom.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            articleInfoDetailVo.setTitle(articleInfoCustom.getTitle());
            articleInfoDetailVo.setCircleId(String.valueOf(articleInfoCustom.getCircleId()));
            articleInfoDetailVo.setCircleName(circleInfo.getCircleName());
            articleInfoDetailVo.setReadTotal(String.valueOf(articleInfoCustom.getReadTotal()));
            articleInfoDetailVo.setCommentTotal(String.valueOf(articleInfoCustom.getCommentTotal()));
            articleInfoDetailVo.setIsCharge(String.valueOf(articleInfoCustom.getIsCharge()));
            articleInfoDetailVo.setChargeAmount(String.valueOf(articleInfoCustom.getChargeAmount()));
            articleInfoDetailVo.setLikeTotal(String.valueOf(articleInfoCustom.getLikeTotal()));
            articleInfoDetailVo.setFreeContentSort(articleInfoCustom.getFreeContentOrderRule());

            List<String> freeArticleTextList = new ArrayList<String>(); //免费文章内容
            List<String> paidArticleTextList = new ArrayList<String>(); //收费文章内容
            List<ArticleTextInfo> articleTextInfoList = articleTextInfoService.findByArticleId(articleId);
            if (null != articleTextInfoList && articleTextInfoList.size() > 0) {
                for (int i = 0; i < articleTextInfoList.size(); i++) {
                    ArticleTextInfo articleTextInfo = articleTextInfoList.get(i);
                    if (1 == articleTextInfo.getTextChargeType()) {
                        freeArticleTextList.add(articleTextInfo.getContent());
                    } else {
                        paidArticleTextList.add(articleTextInfo.getContent());
                    }
                }
            }
            articleInfoDetailVo.setFreeArticleContents(freeArticleTextList);

            List<String> freeArticlePictureList = new ArrayList<String>(); //免费文章配图
            List<ArticlePictureInfo> articlePictureInfoList = articlePictureInfoService.findByArticleId(articleId);
            if (null != articlePictureInfoList && articlePictureInfoList.size() > 0) {
                for (int i = 0; i < articlePictureInfoList.size(); i++) {
                    ArticlePictureInfo articlePictureInfo = articlePictureInfoList.get(i);
                    freeArticlePictureList.add(articlePictureInfo.getOriginalImageUrl());
                }
            }
            articleInfoDetailVo.setFreeArticleImages(freeArticlePictureList);

            List<CompetitionArticleVo> freeArticleCompetitionList = new ArrayList<CompetitionArticleVo>(); //免费文章赛事
            List<CompetitionArticleVo> paidArticleCompetitionList = new ArrayList<CompetitionArticleVo>(); //收费文章赛事
            List<ArticleCompetitionInfoCustom> articleCompetitionInfoList = articleCompetitionInfoService.findByArticleId(articleId);
            if (null != articleCompetitionInfoList && articleCompetitionInfoList.size() > 0) {
                for (int i = 0; i < articleCompetitionInfoList.size(); i++) {
                    ArticleCompetitionInfoCustom articleCompetitionInfoCustom = articleCompetitionInfoList.get(i);
                    CompetitionInfo competitionInfo = articleCompetitionInfoCustom.getCompetitionInfo();
                    if (Objects.nonNull(competitionInfo)) {
                        CompetitionArticleVo competitionArticleVo = new CompetitionArticleVo();
                        competitionArticleVo.setId(String.valueOf(competitionInfo.getId()));
                        competitionArticleVo.setHomeTeam(competitionInfo.getHomeTeam());
                        competitionArticleVo.setVisitingTeam(competitionInfo.getVisitingTeam());
                        competitionArticleVo.setPlayingDate(competitionInfo.getPlayingDate());
                        competitionArticleVo.setPlayingTime(competitionInfo.getPlayingTime());
                        competitionArticleVo.setLeague(competitionInfo.getLeague());
                        if (1 == articleCompetitionInfoCustom.getCompetitionChargeType()) {
                            freeArticleCompetitionList.add(competitionArticleVo);
                        } else {
                            paidArticleCompetitionList.add(competitionArticleVo);
                        }
                    }
                }
            }
            articleInfoDetailVo.setFreeArticlsCompetitions(freeArticleCompetitionList);
            articleInfoDetailVo.setPaidArticlsCompetitions(paidArticleCompetitionList);

            String userId = reqParamMap.get("userId");
            String accessToken = reqParamMap.get("accessToken");
            if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(accessToken)) {
                Object hget = jedisClient.hget("portalUser", userId);
                String s = String.valueOf(hget);
                if (!accessToken.equals(s)) {
                    return ResponseResult.buildResult(ResultEnum.LOGIN_OUTOFDATE_ERROR);
                }

                //查询当前用户是否属于该圈子成员
                PageData pd = new PageData();
                pd.put("userId", userId);
                pd.put("circleId", articleInfoCustom.getCircleId());
                CircleMemberInfo circleMemberInfo = circleMemberInfoService.findByUserIdAndCircleId(pd);

                //当前用户在该文章中处于什么角色
                if (userId.equals(author.getUserId())) { //作者本人查看
                    if (Objects.nonNull(circleMemberInfo) && (circleMemberInfo.getRank() == 3 || circleMemberInfo.getRank() == 4)) {
                        author.setUserRole("5"); //5：【作者本人 + 副圈主或圈主】组合
                    } else {
                        author.setUserRole("2"); //2：作者本人；
                    }

                    articleInfoDetailVo.setArticleState(String.valueOf(articleInfoCustom.getArticleState()));

                    //统计该文章被查看次数和总额
                    Map<String, Object> viewArticleMap = transactionRecordService.findByTypeCodeAndArticleId("TLX00005", articleId);
                    articleInfoDetailVo.setPayTotal(String.valueOf(viewArticleMap.get("total")));
                    articleInfoDetailVo.setPayAmount(String.valueOf(viewArticleMap.get("amount")));

                    //统计该文章被打赏次数和总额
                    Map<String, Object> rewardArticleMap = transactionRecordService.findByTypeCodeAndArticleId("TLX00006", articleId);
                    articleInfoDetailVo.setRewardTotal(String.valueOf(rewardArticleMap.get("total")));
                    articleInfoDetailVo.setRewardAmount(String.valueOf(rewardArticleMap.get("amount")));

                    //设置对文章操作的权限
                    long endTimeLong = CalendarUtil.getWantedDate(articleInfoCustom.getCreateTime(), null, 5, null, null, null).getTime();
                    //获取圈子内文章推广规则配置信息
                    PromotionRuleConfig promotionRuleConfig = promotionRuleConfigService.findByPromotionType(1);
                    long validTimeLong = CalendarUtil.getWantedDate(CalendarUtil.getSystemCurrentDate(), null, null, null, null, promotionRuleConfig.getPromotionDuration()).getTime();

                    MenuLevelConfig menuLevelConfig = menuLevelConfigService.findByMenuCode(circleInfo.getMainTypeCode());
                    if (validTimeLong < endTimeLong) {
                        if (2 == articleInfoCustom.getArticleState()) { //文章审核被驳回
                            articleInfoDetailVo.setOperatState("1"); //无权限
                        } else if (2 == articleInfoCustom.getIsPromotion() && 3 == articleInfoCustom.getArticleState()) {
                            articleInfoDetailVo.setOperatState("4"); //已推广
                        } else if (1 == articleInfoCustom.getIsHot() && 2 == menuLevelConfig.getIsSetHot()) {
                            articleInfoDetailVo.setOperatState("2"); //可以申请进热帖
                        } else if (2 == articleInfoCustom.getIsHot() && 1 == articleInfoCustom.getIsPromotion()) {
                            articleInfoDetailVo.setOperatState("2"); //可以申请推广
                        } else {
                            articleInfoDetailVo.setOperatState("1"); //无权限
                        }
                    } else {
                        articleInfoDetailVo.setOperatState("1"); //无权限
                    }

                    //展示收费内容
                    articleInfoDetailVo.setPaidContentSort(articleInfoCustom.getFreeContentOrderRule());
                    articleInfoDetailVo.setPaidArticleContents(paidArticleTextList);
                } else { //非作者本人查看
                    if (Objects.nonNull(circleMemberInfo) && (circleMemberInfo.getRank() == 3 || circleMemberInfo.getRank() == 4)) {
                        author.setUserRole(String.valueOf(circleMemberInfo.getRank())); //3：副圈主；4：圈主；
                    } else {
                        author.setUserRole("1"); //1：小白；
                    }

                    //查询当前用户是否关注文章作者
                    FollowInfo followInfo = followInfoService.findByUserIdAndFollowUserId(userId, articleInfoDetailVo.getAuthor().getUserId());
                    if (Objects.isNull(followInfo)) {
                        author.setIsFollow("1");
                    } else {
                        author.setIsFollow("2");
                    }
                    articleInfoDetailVo.setOperatState("1"); //非文章作者没有权限对文章进行申请进热帖和推广操作

                    //用户是否付费查看过该文章
                    TransactionRecord transactionRecord = transactionRecordService.findViewArticleByUserIdAndArticleId(userId, articleId);
                    if (Objects.nonNull(transactionRecord)) {
                        //展示收费内容
                        articleInfoDetailVo.setPaidContentSort(articleInfoCustom.getFreeContentOrderRule());
                        articleInfoDetailVo.setPaidArticleContents(paidArticleTextList);
                    }
                }

                //当前用户是否收藏了该文章
                CollectInfo collectInfo = collectInfoService.findByUserIdAndArticleId(userId, articleId);
                if (Objects.isNull(collectInfo)) {
                    articleInfoDetailVo.setIsCollect("1");
                } else {
                    articleInfoDetailVo.setIsCollect("2");
                }
            } else {
                author.setUserRole("1"); //1：小白；
                articleInfoDetailVo.setOperatState("1"); //无权限
            }
            articleInfoDetailVo.setIsTop(String.valueOf(articleInfoCustom.getIsTop())); //是否置顶
            articleInfoDetailVo.setAuthor(author);
            return ResponseResult.buildResult(ResultEnum.SUCCESS, articleInfoDetailVo);
        } catch (Exception e) {
            log.error("【获取文章详情出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_ARTICLE_DETAIL_EXCEPTION);
        }
    }

    /**
     * description: 获取文章付费明细
     * author sunny
     * createDate 2019-04-26 上午 10:14
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getPaymentDetail", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getPaymentDetail(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String articleId = reqParamMap.get("articleId");
        if (StringUtils.isBlank(articleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "articleId");
        }

        String page = reqParamMap.get("page");
        String refreshTime = reqParamMap.get("refreshTime");
        if (StringUtils.isBlank(page)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "page");
        } else {
            if ("1".equals(page)) {
                refreshTime = CalendarUtil.getNowDate();
            } else {
                if (StringUtils.isBlank(refreshTime)) {
                    return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "refreshTime");
                }
            }
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            ArticleInfo articleInfo = articleInfoService.findByArticleId(articleId);
            if (Objects.isNull(articleInfo)) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_NOT_EXIST_FAIL);
            }

            String userId = reqParamMap.get("userId");
            if (!userId.equals(articleInfo.getUserId())) { //非作者本人
                return ResponseResult.buildResult(ResultEnum.NOT_AUTHOR_FAIL);
            }

            //封装响应数据
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("refreshTime", refreshTime);

            Map<String, Object> countMap = transactionRecordService.findByTypeCodeAndArticleId("TLX00005", articleId);
            responseMap.put("chargeAmount", String.valueOf(articleInfo.getChargeAmount()));
            responseMap.put("payTotal", String.valueOf(countMap.get("total")));
            responseMap.put("payAmount", String.valueOf(countMap.get("amount")));

            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("articleId", articleId);
            paramMap.put("refreshTime", refreshTime);
            paramMap.put("pageIndex", Const.PORTAL_PAGE * (Integer.valueOf(page) - 1));
            paramMap.put("pageCount", Const.PORTAL_PAGE);

            List<Map<String, Object>> paymentDetailList = transactionRecordService.findPaymentDetailByArticleId(paramMap);
            responseMap.put("user", paymentDetailList);
            return ResponseResult.buildResult(ResultEnum.SUCCESS, responseMap);
        } catch (Exception e) {
            log.error("【获取文章付费明细出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_PAYMENT_DETAIL_EXCEPTION);
        }
    }

    /**
     * description: 获取文章打赏明细
     * author sunny
     * createDate 2019-04-26 下午 1:37
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getRewardDetail", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getRewardDetail(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String articleId = reqParamMap.get("articleId");
        if (StringUtils.isBlank(articleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "articleId");
        }

        String page = reqParamMap.get("page");
        String refreshTime = reqParamMap.get("refreshTime");
        if (StringUtils.isBlank(page)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "page");
        } else {
            if ("1".equals(page)) {
                refreshTime = CalendarUtil.getNowDate();
            } else {
                if (StringUtils.isBlank(refreshTime)) {
                    return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "refreshTime");
                }
            }
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            ArticleInfo articleInfo = articleInfoService.findByArticleId(articleId);
            if (Objects.isNull(articleInfo)) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_NOT_EXIST_FAIL);
            }

            String userId = reqParamMap.get("userId");
            if (!userId.equals(articleInfo.getUserId())) { //非作者本人
                return ResponseResult.buildResult(ResultEnum.NOT_AUTHOR_FAIL);
            }

            //封装响应数据
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("refreshTime", refreshTime);

            Map<String, Object> countMap = transactionRecordService.findByTypeCodeAndArticleId("TLX00006", articleId);
            responseMap.put("rewardTotal", String.valueOf(countMap.get("total")));
            responseMap.put("rewardAmount", String.valueOf(countMap.get("amount")));

            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("articleId", articleId);
            paramMap.put("refreshTime", refreshTime);
            paramMap.put("pageIndex", Const.PORTAL_PAGE * (Integer.valueOf(page) - 1));
            paramMap.put("pageCount", Const.PORTAL_PAGE);

            List<Map<String, Object>> rewardDetailList = transactionRecordService.findRewardDetailByArticleId(paramMap);
            responseMap.put("user", rewardDetailList);
            return ResponseResult.buildResult(ResultEnum.SUCCESS, responseMap);
        } catch (Exception e) {
            log.error("【获取文章打赏明细出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_REWARD_DETAIL_EXCEPTION);
        }
    }


    /**
     * description: 文章收藏
     * author sunny
     * createDate 2019-04-26 下午 2:16
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/goCollect", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult goCollect(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String articleId = reqParamMap.get("articleId");
        if (StringUtils.isBlank(articleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "articleId");
        }

        String isCollect = reqParamMap.get("isCollect");
        if (StringUtils.isBlank(isCollect)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "isCollect");
        } else if (!"1".equals(isCollect) && !"2".equals(isCollect)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_ERROR, "isCollect");
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            ArticleInfo articleInfo = articleInfoService.findByArticleId(articleId);
            if (Objects.isNull(articleInfo)) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_NOT_EXIST_FAIL);
            }

            //封装数据
            CollectInfo collectInfo = new CollectInfo();
            collectInfo.setUserId(reqParamMap.get("userId"));
            collectInfo.setArticleId(articleId);
            if ("1".equals(isCollect)) {
                Integer collectCount = collectInfoService.deleteCollectInfo(collectInfo);
                if (-1 == collectCount) {
                    return ResponseResult.buildResult(ResultEnum.NO_COLLECT_FAIL);
                }

                return ResponseResult.buildResult(ResultEnum.NO_COLLECT_SUCCESS);
            } else {
                collectInfo.setCreateTime(CalendarUtil.getSystemCurrentDate());
                Integer collectCount = collectInfoService.saveCollectInfo(collectInfo);
                if (-1 == collectCount) {
                    return ResponseResult.buildResult(ResultEnum.COLLECT_FAIL);
                }
                return ResponseResult.buildResult(ResultEnum.COLLECT_SUCCESS);
            }
        } catch (Exception e) {
            log.error("【文章收藏/取消收藏出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GO_COLLECT_EXCEPTION);
        }
    }

    /**
     * description: 申请进入热帖
     * author sunny
     * createDate 2019-04-26 下午 4:08
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/applyHot", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult applyHot(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String articleId = reqParamMap.get("articleId");
        if (StringUtils.isBlank(articleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "articleId");
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            ArticleInfo articleInfo = articleInfoService.findByArticleId(articleId);
            if (Objects.isNull(articleInfo)) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_NOT_EXIST_FAIL);
            }

            String userId = reqParamMap.get("userId");
            if (!userId.equals(articleInfo.getUserId())) {
                return ResponseResult.buildResult(ResultEnum.NOT_AUTHOR_FAIL);
            }

            if (2 == articleInfo.getIsHot()) { //已经申请过进入热帖
                return ResponseResult.buildResult(ResultEnum.APPLY_HOT_FAIL);
            }

            articleInfo.setIsHot(2); //进热帖
            if (1 == articleInfo.getIsCharge()) {
                articleInfo.setArticleState(1); //待审核
            }

            articleInfoService.updateArticleInfo(articleInfo);

            if (3 == articleInfo.getArticleState()) {
                return ResponseResult.buildResult(ResultEnum.APPLY_HOT_SUCCESS);
            } else {
                return ResponseResult.buildResult(ResultEnum.APPLY_HOT_TO_AUDIT_SUCCESS);
            }
        } catch (Exception e) {
            log.error("【申请进入热帖出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.APPLY_HOT_EXCEPTION);
        }
    }

    /**
     * description: 获取推广规则
     * author sunny
     * createDate 2019-04-29 上午 9:46
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getPromotionRule", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getPromotionRule(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String promotionType = reqParamMap.get("promotionType");
        if (StringUtils.isBlank(promotionType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "promotionType");
        } else if (!"1".equals(promotionType) && !"2".equals(promotionType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_ERROR, "promotionType");
        }

        String articleId = reqParamMap.get("articleId");
        if (StringUtils.isBlank(articleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "articleId");
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            ArticleInfo articleInfo = articleInfoService.findByArticleId(articleId);
            if (Objects.isNull(articleInfo)) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_NOT_EXIST_FAIL);
            }

            String userId = reqParamMap.get("userId");
            if (!userId.equals(articleInfo.getUserId())) {
                return ResponseResult.buildResult(ResultEnum.NOT_AUTHOR_FAIL);
            }

            PortalUserInfo portalUserInfo = portalUserInfoService.findByUserId(userId);
            //余额--金币
            String remainGold = MathUtil.addDown(String.valueOf(portalUserInfo.getGoldBuy()), String.valueOf(portalUserInfo.getGoldProfit()));

            ArticlePromotionRuleVo articlePromotionRuleVo = promotionRuleConfigService.findVoByPromotionType(Integer.valueOf(promotionType));
            articlePromotionRuleVo.setRemainGold(remainGold);
            return ResponseResult.buildResult(ResultEnum.SUCCESS, articlePromotionRuleVo);
        } catch (Exception e) {
            log.error("【获取推广规则出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_PROMOTION_RULE_EXCEPTION);
        }
    }

    /**
     * description: 获取打赏理由
     * author sunny
     * createDate 2019-04-29 下午 3:38
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getRewardReason", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getRewardReason(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String articleId = reqParamMap.get("articleId");
        if (StringUtils.isBlank(articleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "articleId");
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            ArticleInfo articleInfo = articleInfoService.findByArticleId(articleId);
            if (Objects.isNull(articleInfo)) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_NOT_EXIST_FAIL);
            }

            String userId = reqParamMap.get("userId");
            if (userId.equals(articleInfo.getUserId())) {
                return ResponseResult.buildResult(ResultEnum.AUTHOR_REWARD_FAIL);
            }

            PortalUserInfo portalUserInfo = portalUserInfoService.findByUserId(userId);
            //余额--金币
            String remainGold = MathUtil.addDown(String.valueOf(portalUserInfo.getGoldBuy()), String.valueOf(portalUserInfo.getGoldProfit()));

            //查询打赏理由列表
            List<ArticleRewardReasonVo> rewardReasonVos = rewardReasonDictService.findArticleRewardReasonVo();

            //封装响应数据
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("articleId", articleId);
            responseMap.put("remainGold", remainGold);
            responseMap.put("rewardReasons", rewardReasonVos);
            return ResponseResult.buildResult(ResultEnum.SUCCESS, responseMap);
        } catch (Exception e) {
            log.error("【获取打赏理由出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_REWARD_REASON_EXCEPTION);
        }
    }

    /**
     * description: 文章删除
     * author sunny
     * createDate 2019-04-29 下午 4:54
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/deleteArticle", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult deleteArticle(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String articleId = reqParamMap.get("articleId");
        if (StringUtils.isBlank(articleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "articleId");
        }

        String deleteType = reqParamMap.get("deleteType");
        String deleteReason = reqParamMap.get("deleteReason");
        if (StringUtils.isBlank(deleteType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "deleteType");
        } else {
            if (!"1".equals(deleteType) && !"2".equals(deleteType)) {
                return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_ERROR, "deleteType");
            }

            if ("1".equals(deleteType) && StringUtils.isBlank(deleteReason)) {
                return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "deleteReason");
            }
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            ArticleInfo articleInfo = articleInfoService.findByArticleId(articleId);
            if (Objects.isNull(articleInfo)) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_NOT_EXIST_FAIL);
            }

            String userId = reqParamMap.get("userId");
            //查询当前用户是否属于该圈子成员
            PageData pd = new PageData();
            pd.put("userId", userId);
            pd.put("circleId", articleInfo.getCircleId());
            CircleMemberInfo circleMemberInfo = circleMemberInfoService.findByUserIdAndCircleId(pd);
            if (Objects.isNull(circleMemberInfo)) {
                return ResponseResult.buildResult(ResultEnum.NO_PERMISSIONS_FAIL);
            }

            if (!userId.equals(articleInfo.getUserId()) && circleMemberInfo.getRank() != 3) {
                return ResponseResult.buildResult(ResultEnum.NO_PERMISSIONS_FAIL);
            }

            DeleteArticleRecord deleteArticleRecord = new DeleteArticleRecord();
            deleteArticleRecord.setCreateTime(CalendarUtil.getSystemCurrentDate());
            deleteArticleRecord.setArticleId(articleId);
            deleteArticleRecord.setUserId(userId);
            deleteArticleRecord.setDeleteType(Integer.valueOf(deleteType));
            deleteArticleRecord.setDeleteReason(deleteReason);
            Integer count = deleteArticleRecordService.saveArticleRecord(deleteArticleRecord);
            if (count == -1) {
                return ResponseResult.buildResult(ResultEnum.DELETE_ARTICLE_FAIL);
            }
            return ResponseResult.buildResult(ResultEnum.DELETE_ARTICLE_SUCCESS);
        } catch (Exception e) {
            log.error("【文章删除出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.DELETE_ARTICLE_EXCEPTION);
        }
    }

    /**
     * description: 文章置顶/取消置顶
     * author sunny
     * createDate 2019-04-29 下午 7:44
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/goTop", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult goTop(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String articleId = reqParamMap.get("articleId");
        if (StringUtils.isBlank(articleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "articleId");
        }

        String topType = reqParamMap.get("topType");
        if (StringUtils.isBlank(topType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "topType");
        } else if (!"1".equals(topType) && !"2".equals(topType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_ERROR, "topType");
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            ArticleInfo articleInfo = articleInfoService.findByArticleId(articleId);
            if (Objects.isNull(articleInfo)) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_NOT_EXIST_FAIL);
            }

            String userId = reqParamMap.get("userId");
            //查询当前用户是否属于该圈子成员
            PageData pd = new PageData();
            pd.put("userId", userId);
            pd.put("circleId", articleInfo.getCircleId());
            CircleMemberInfo circleMemberInfo = circleMemberInfoService.findByUserIdAndCircleId(pd);
            if (Objects.isNull(circleMemberInfo)) {
                return ResponseResult.buildResult(ResultEnum.NO_PERMISSIONS_FAIL);
            }

            if (circleMemberInfo.getRank() != 3 && circleMemberInfo.getRank() != 4) {
                return ResponseResult.buildResult(ResultEnum.NO_PERMISSIONS_FAIL);
            }

            if("1".equals(topType)){
                //封装数据
                articleInfo.setIsTop(1);
                articleInfoService.updateArticleInfo(articleInfo);
                return ResponseResult.buildResult(ResultEnum.NO_TOP_SUCCESS);
            }else{
                Integer topCount = articleInfoService.findTopCountByCircleId(articleInfo.getCircleId());
                if(topCount >= 6){
                    return ResponseResult.buildResult(ResultEnum.ARTICLE_TOP_FAIL);
                }
                //封装数据
                articleInfo.setIsTop(2);
                articleInfo.setTopTime(CalendarUtil.getSystemCurrentDate());
                articleInfoService.updateArticleInfo(articleInfo);
                return ResponseResult.buildResult(ResultEnum.TOP_SUCCESS);
            }

        } catch (Exception e) {
            log.error("【文章置顶/取消置顶出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GO_TOP_EXCEPTION);
        }
    }
}
